
package parsers;

import java.net.URL;
import java.util.LinkedList;

import movie.Movie;
import movie.Torrent;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/**
 *
 * @author lopesdasilva
 */
public class MovieParser {

	private static final boolean DEBUG = false;
	LinkedList<Torrent> torrentList =new LinkedList<Torrent>();

	public  LinkedList<Torrent> parse(Movie m){
		try {
			Document document = (Document) Jsoup.parse(new URL(m.getURL()), 200);	

			Element torrents = document.getElementById("torrents");

			//get rating
			Elements rating = document.getElementsByClass("rating");


			//get image
			String image=document.getElementById("poster").attr("src");

			if(DEBUG){
				System.out.println("Rating: "+rating.text());
				System.out.println("Poster: "+image);
			}
			m.setRate(rating.text());
			m.setPoster(image);

			Elements a = torrents.select("tbody");
			Elements b = a.select("tr");
			for (Element t:b){

				String type = t.attr("class");
				String size = t.getElementsByClass("size").text();
				String link = t.select("a").last().attr("href");
				String seeds =t.getElementsByClass("seeders").text();

				if(DEBUG){
					System.out.println("Type: "+type);
					System.out.println("Size: "+size);//size
					System.out.println("Seeds: "+seeds);//seeds
					System.out.println("Torrent link: "+link);//Torrent
				}

				if (type.equals("verified"))
					torrentList.addFirst(new Torrent (link,convertSize(size),convertseeds(seeds),type));
				else
					torrentList.addLast(new Torrent (link,convertSize(size),convertseeds(seeds),type));
				
			}

		} catch (Exception ex) {
			System.out.println(ex.getMessage());
		}

		return torrentList;
	}

	private double convertseeds(String seeds) {
		if(seeds.equals("") || seeds==null )
			return 0;
		if (seeds.contains(",")){
			
			seeds=seeds.replace(',', '.');

			return Double.parseDouble(seeds)*1000;
		}
		else
			
		return Double.parseDouble(seeds);
	}

	private double convertSize(String size) {
		if(size.equals("") || size==null )
			return 0;
		if (size.contains("GB")){
			String [] aux=size.split(" ");
			
			return Double.parseDouble(aux[0])*1000;
		}else{
			String [] aux=size.split(" ");
			
			return Double.parseDouble(aux[0]);
		}
	}
}
